package com.web.controller;
import com.alibaba.fastjson2.JSON;
import com.web.entity.ResponseResult;
import com.web.entity.Student;
import com.web.service.StudentService;
import com.web.service.impl.StudentServiceimpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//添加学生
@WebServlet("/addStudent")
//添加数据
public class Add extends HttpServlet {
    private StudentService studentService = new StudentServiceimpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求编码
        req.setCharacterEncoding("UTF-8");
        //设置响应编码
        resp.setCharacterEncoding("UTF-8");
        //设置响应类型
        resp.setContentType("application/json;charset=UTF-8");

        // 获取表单数据
        int id = req.getIntHeader("id");
        String name = req.getParameter("name");
        int age = Integer.parseInt(req.getParameter("age"));
        String gender = req.getParameter("gender");
        String idcard = req.getParameter("idcard");
        String address = req.getParameter("address");

        // 创建 Student 对象
        Student student = new Student(id, address, idcard, gender, age, name);
        // 调用 Service 插入学生
        studentService.addStudent(student);
        // 返回结果
        ResponseResult result = new ResponseResult(200, student, "ok");
        resp.getWriter().write(JSON.toJSONString(result));



    }
}
